package com.wing.cabinet.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.cabinet.dao.CheckedResultOrderDao;
import com.wing.cabinet.model.entity.*;
import com.wing.cabinet.model.request.CheckedResultDTO;
import com.wing.cabinet.model.request.CheckedResultOrderDTO;
import com.wing.cabinet.model.request.CheckedResultOrderDetailForm;
import com.wing.cabinet.model.request.CheckedResultOrderForm;
import com.wing.cabinet.model.response.CheckedResultOrderVO;
import com.wing.config.BaseDataInit;
import com.wing.order.service.DynamicService;
import com.wing.util.PulsarCommons;
import com.wing.util.PulsarUtils;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.shade.com.google.gson.JsonArray;
import org.apache.pulsar.shade.org.apache.avro.data.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 盘验结果生成的订单-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class CheckedResultOrderServiceImpl extends ServiceImpl<CheckedResultOrderDao, CheckedResultOrder> implements CheckedResultOrderService {

    @Value("${pulsar.client.topicUrl}")
    private String topicUrl;
    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private CheckedResultOrderDetailService orderDetailService;

    @Autowired
    private CheckedResultService resultService;

    @Autowired
    private CheckedResultDetailService checkedResultDetailService;

    private ExecutorService executorService= Executors.newFixedThreadPool(10);

    @Override
    public int add(CheckedResultOrderForm checkedResultOrderForm) {

        //校验

        CheckedResultOrder checkedResultOrder =new CheckedResultOrder();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(CheckedResultOrder.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(checkedResultOrderForm, checkedResultOrder, copyOptions);

        return baseMapper.insert(checkedResultOrder);
    }

    @Override
    public List<CheckedResultOrderVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<CheckedResultOrderVO> pageList4app(Page page, Map<String, Object> params) {
        List<CheckedResultOrderVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public CheckedResultOrderVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional
    public void save(CheckedResultOrderForm checkedResultOrderForm) {
        Long enterpriseId=JwtUtils.getEnterpriseId();
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        CheckedResultOrder checkedResult=new CheckedResultOrder();
        BeanUtil.copyProperties(checkedResultOrderForm,checkedResult);
        checkedResult.setCreator(JwtUtils.getLoginUserId());
        checkedResult.setCreatorName(JwtUtils.getLoginUsername());
        checkedResult.setQuantity(getSumQuantity(checkedResultOrderForm));
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        String code=dynamicService.getDayNextCode("cab_checked_result_order");
        String day=simpleDateFormat.format(new Date());
        checkedResult.setCode("RC-"+day+"-"+code);
        checkedResult.setDay(Integer.valueOf(day));
        checkedResult.setNo(Integer.valueOf(code));
//        checkedResult.setSupplierCompanyId(checkedResult.getCompanyId());
        checkedResult.setCompanyId(enterpriseId);
        checkedResult.setEnterpriseCode(enterpriseCode);
        //新增checkedResultOrder
        baseMapper.insert(checkedResult);
        checkedResultOrderForm.setId(checkedResult.getId());
        //新增checkedResultOrderDetail
        List<Long> resultIdList=saveDetail(checkedResultOrderForm);
        if (resultIdList.size()>0){
            //修改checkedResult
            resultService.updateIsGenOrder(resultIdList);
        }
        sendMsg(checkedResultOrderForm,checkedResult,resultIdList);
    }

    List<Long> saveDetail(CheckedResultOrderForm checkedResultOrderForm){
        List<Long> resultIdList=new ArrayList<>();
        Long orderId=checkedResultOrderForm.getId();
        if (CollectionUtils.isNotEmpty(checkedResultOrderForm.getDetailList())){
            for (CheckedResultOrderDetailForm checkedResultOrderDetailForm:checkedResultOrderForm.getDetailList()){
                CheckedResultOrderDetail checkedResultOrderDetail=new CheckedResultOrderDetail();
                checkedResultOrderDetail.setCreator(checkedResultOrderForm.getCreator());
                checkedResultOrderDetail.setCreatorName(checkedResultOrderForm.getCreatorName());
                checkedResultOrderDetail.setOrderId(orderId);
                checkedResultOrderDetail.setResultId(checkedResultOrderDetailForm.getResultId());
                checkedResultOrderDetail.setEnterpriseCode(checkedResultOrderForm.getEnterpriseCode());
                orderDetailService.save(checkedResultOrderDetail);
                resultIdList.add(checkedResultOrderDetailForm.getResultId());
            }
        }
        return resultIdList;
    }

    private Integer getSumQuantity(CheckedResultOrderForm checkedResultOrderForm){
        Integer sum=0;
        if (CollectionUtils.isNotEmpty(checkedResultOrderForm.getDetailList())){
            for (CheckedResultOrderDetailForm checkedResultOrderDetailForm:checkedResultOrderForm.getDetailList()){
                sum+=checkedResultOrderDetailForm.getQuantity();
            }
        }
        return sum;
    }
    void sendMsg(CheckedResultOrderForm checkedResultOrderForm,CheckedResultOrder checkedResult,List<Long> resultIdList){
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            syncDate(checkedResultOrderForm,checkedResult,resultIdList);
                        }catch (Exception e){
                            log.error("syn fail",e);
                        }

                    }
                });
            }
        });
    }

    private void syncDate(CheckedResultOrderForm checkedResultOrderForm,CheckedResultOrder checkedResult,List<Long> resultIdList){

        //数据同步CheckedResultOrder
        try {
            String uniqCode = BaseDataInit.ENTERPRISE_DATA.getCode()+checkedResultOrderForm.getId();
            List<CheckedResultOrderDetail> orderDetails = orderDetailService.list(new QueryWrapper<CheckedResultOrderDetail>().eq("result_id", checkedResult.getId()));
            CheckedResultOrderDTO checkedResultOrderDTO = new CheckedResultOrderDTO();
            //利用json 实现类的相互转换
            checkedResultOrderDTO = JSON.parseObject(JSON.toJSONString(orderDetails), CheckedResultOrderDTO.class);
            checkedResultOrderDTO.setDetails(orderDetails);
            JSONObject json = (JSONObject) JSONObject.toJSON(checkedResultOrderDTO);
            json.put("uniqCode",uniqCode);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            jsonObject.put("data", json);
            PulsarUtils.send(topicUrl+ PulsarCommons.CHECKED_RESULT_ORDER_TOPIC,jsonObject.toJSONString());
            checkedResult.setIsSync(CheckedResultOrder.IsSync.yes);
            checkedResult.setUniqCode(uniqCode);
            baseMapper.updateById(checkedResult);
        }catch (PulsarClientException e){
            //同步失败时，改变数据状态。 定时器再执行同步
            checkedResult.setIsSync(CheckedResultOrder.IsSync.no);
            baseMapper.updateById(checkedResult);
            e.printStackTrace();
        }
        //数据同步CheckedResultOrderDetail
       /* List<CheckedResultOrderDetail> orderDetails = orderDetailService.list(new QueryWrapper<CheckedResultOrderDetail>().eq("result_id", checkedResult.getId()));
        try {
            JSONArray jsonArray = new JSONArray();
            for (CheckedResultOrderDetail orderDetail : orderDetails) {
                JSONObject json = (JSONObject)JSONObject.toJSON(orderDetail);
                String uniqCode = BaseDataInit.ENTERPRISE_DATA.getCode()+orderDetail.getOrderId();
                json.put("orderUniqCode",uniqCode);
                jsonArray.add(json);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            jsonObject.put("data", orderDetails);
            PulsarUtils.send(topicUrl+ PulsarCommons.CHECKED_RESULT_ORDER_DETAIL_TOPIC,jsonObject.toJSONString());
            for (CheckedResultOrderDetail orderDetail : orderDetails) {
                orderDetail.setIsSync(CheckedResultOrderDetail.IsSync.yes);
                orderDetailService.updateById(orderDetail);
            }
        }catch (PulsarClientException e){
            //同步失败时，改变数据状态。 定时器再执行同步
            for (CheckedResultOrderDetail orderDetail : orderDetails) {
                orderDetail.setIsSync(CheckedResultOrderDetail.IsSync.no);
                orderDetailService.updateById(orderDetail);
            }
            e.printStackTrace();
        }*/
        //数据同步CheckedResult
        List<CheckedResult> checkedResults = resultService.list(new QueryWrapper<CheckedResult>().in("id", resultIdList));
        try {
            JSONArray jsonArray = new JSONArray();
            for (CheckedResult checkedResult1 : checkedResults) {
                List<CheckedResultDetail> checkedResultDetails = checkedResultDetailService.list(new QueryWrapper<CheckedResultDetail>().eq("result_id", checkedResult1.getId()));
                CheckedResultDTO checkedResultDTO = new CheckedResultDTO();
                //利用json 实现类的相互转换
                checkedResultDTO = JSON.parseObject(JSON.toJSONString(checkedResult1), CheckedResultDTO.class);
                checkedResultDTO.setDetails(checkedResultDetails);
                JSONObject json = (JSONObject)JSONObject.toJSON(checkedResultDTO);
                String uniqCode = BaseDataInit.ENTERPRISE_DATA.getCode()+checkedResult1.getId();
                json.put("uniqCode",uniqCode);
                jsonArray.add(json);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            jsonObject.put("data", jsonArray);
            PulsarUtils.send(topicUrl+ PulsarCommons.CHECKED_RESULT_TOPIC,jsonObject.toJSONString());
            for (CheckedResult result : checkedResults) {
                result.setIsSync(CheckedResult.IsSync.yes);
                resultService.updateById(result);
            }
        }catch (PulsarClientException e){
            //同步失败时，改变数据状态。 定时器再执行同步
            for (CheckedResult Result : checkedResults) {
                Result.setIsSync(CheckedResult.IsSync.no);
                resultService.updateById(Result);
            }
            e.printStackTrace();
        }
        //数据同步CheckedResultDetail
       /* List<CheckedResultDetail> checkedResultDetails = checkedResultDetailService.list(new QueryWrapper<CheckedResultDetail>().in("result_id", resultIdList));
        try {
            JSONArray jsonArray = new JSONArray();
            for (CheckedResultDetail checkedResultDetail : checkedResultDetails) {
                JSONObject json = (JSONObject)JSONObject.toJSON(checkedResultDetail);
                String uniqCode = BaseDataInit.ENTERPRISE_DATA.getCode()+checkedResultDetail.getResultId();
                json.put("resultUniqCode",uniqCode);
                jsonArray.add(json);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            jsonObject.put("data", jsonArray);
            PulsarUtils.send(topicUrl+ PulsarCommons.CHECKED_RESULT_DETAIL_TOPIC,jsonObject.toJSONString());
            for (CheckedResultDetail ResultDetail : checkedResultDetails) {
                ResultDetail.setIsSync(CheckedResultDetail.IsSync.yes);
                checkedResultDetailService.updateById(ResultDetail);
            }
        }catch (PulsarClientException e){
            //同步失败时，改变数据状态。 定时器再执行同步
            for (CheckedResultDetail ResultDetail : checkedResultDetails) {
                ResultDetail.setIsSync(CheckedResultDetail.IsSync.no);
                checkedResultDetailService.updateById(ResultDetail);
            }
            e.printStackTrace();
        }*/

    }

    /**
     * 同步数据定时任务
     */
    //todo 未设置定时任务时间
    //@Scheduled(cron = "0/3 * * * * ?")
    public void syncTask(){
        //同步CheckedResult
        try {
            List<CheckedResult> checkedResults = resultService.list(new QueryWrapper<CheckedResult>().in("is_sync", CheckedResult.IsSync.no));
            List<CheckedResultDTO> list = new ArrayList<>();
            for (CheckedResult checkedResult : checkedResults) {
                List<CheckedResultDetail> orderDetails = checkedResultDetailService.list(new QueryWrapper<CheckedResultDetail>().eq("result_id", checkedResult.getId()));
                CheckedResultDTO checkedResultDTO = new CheckedResultDTO();
                //利用json 实现类的相互转换
                checkedResultDTO = JSON.parseObject(JSON.toJSONString(orderDetails), CheckedResultDTO.class);
                checkedResultDTO.setDetails(orderDetails);
                list.add(checkedResultDTO);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            jsonObject.put("data", list);
            PulsarUtils.send(topicUrl+ PulsarCommons.CHECKED_RESULT_TOPIC,jsonObject.toJSONString());
            for (CheckedResult checkedResult : checkedResults) {
                checkedResult.setIsSync(CheckedResult.IsSync.yes);
                resultService.updateById(checkedResult);
            }
        }catch (PulsarClientException e){
            e.printStackTrace();
        }
        //同步CheckedResultDetail
       /* try {
            List<CheckedResultDetail> checkedResultDetails = checkedResultDetailService.list(new QueryWrapper<CheckedResultDetail>().in("is_sync", CheckedResultDetail.IsSync.no));
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            jsonObject.put("data", checkedResultDetails);
            PulsarUtils.send(topicUrl+ PulsarCommons.CHECKED_RESULT_DETAIL_TOPIC,jsonObject.toJSONString());
            for (CheckedResultDetail checkedResultDetail : checkedResultDetails) {
                checkedResultDetail.setIsSync(CheckedResultDetail.IsSync.yes);
                checkedResultDetailService.updateById(checkedResultDetail);
            }
        }catch (PulsarClientException e){
            e.printStackTrace();
        }*/
        //同步CheckedResultOrder
        try {
            List<CheckedResultOrder> checkedResultOrders = this.list(new QueryWrapper<CheckedResultOrder>().in("is_sync", CheckedResultOrder.IsSync.no));
            JSONArray jsonArray = new JSONArray();
            for (CheckedResultOrder checkedResult1 : checkedResultOrders) {
                List<CheckedResultOrderDetail> checkedResultDetails = orderDetailService.list(new QueryWrapper<CheckedResultOrderDetail>().eq("result_id", checkedResult1.getId()));
                CheckedResultOrderDTO checkedResultOrderDTO = new CheckedResultOrderDTO();
                //利用json 实现类的相互转换
                checkedResultOrderDTO = JSON.parseObject(JSON.toJSONString(checkedResult1), CheckedResultOrderDTO.class);
                checkedResultOrderDTO.setDetails(checkedResultDetails);
                JSONObject json = (JSONObject)JSONObject.toJSON(checkedResultOrderDTO);
                String uniqCode = BaseDataInit.ENTERPRISE_DATA.getCode()+checkedResult1.getId();
                json.put("uniqCode",uniqCode);
                jsonArray.add(json);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            jsonObject.put("data", jsonArray);
            PulsarUtils.send(topicUrl+ PulsarCommons.CHECKED_RESULT_ORDER_TOPIC,jsonObject.toJSONString());
            for (CheckedResultOrder checkedResultOrder : checkedResultOrders) {
                checkedResultOrder.setIsSync(CheckedResultOrder.IsSync.yes);
                this.updateById(checkedResultOrder);
            }
        }catch (PulsarClientException e){
            e.printStackTrace();
        }
        //同步CheckedResultOrderDetail
       /* try {
            List<CheckedResultOrderDetail> checkedResultOrderDetails = orderDetailService.list(new QueryWrapper<CheckedResultOrderDetail>().in("is_sync", CheckedResultOrderDetail.IsSync.no));
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "addOrUpdate");
            jsonObject.put("data", checkedResultOrderDetails);
            PulsarUtils.send(topicUrl+ PulsarCommons.CHECKED_RESULT_ORDER_DETAIL_TOPIC,jsonObject.toJSONString());
            for (CheckedResultOrderDetail checkedResultOrderDetail : checkedResultOrderDetails) {
                checkedResultOrderDetail.setIsSync(CheckedResultOrderDetail.IsSync.yes);
                orderDetailService.updateById(checkedResultOrderDetail);
            }
        }catch (PulsarClientException e){
            e.printStackTrace();
        }*/
    }
}
